package com.ms.oschina.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

/**
 * Created by Administrator on 2016-05-05.
 */
public class CloneUtils {
    static ByteArrayOutputStream out = null;
    static ObjectOutput oo = null;
    static ByteArrayInputStream bais = null;
    static ObjectInputStream ois = null;

    /**
     * 将对象转换成byte
     * @param ojb
     * @return
     */
    public static byte[] obj2byte(Object ojb) {
        byte[] byteArray = null;

        out = new ByteArrayOutputStream();
        try {
            oo = new ObjectOutputStream(out);
            oo.writeObject(ojb);// 将当前对象写入到流中out
            // 将当前流写入到objectstream中
            byteArray = out.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (oo != null) {
                try {
                    oo.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return byteArray;
    }


    /**
     * 将byte转换成对象
     *
     * @return
     */
    public static Object byte2obj(byte[] byteArray) {
        Object obj = null;
        bais = new ByteArrayInputStream(byteArray);
        try {
            ois = new ObjectInputStream(bais);
            obj = ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (bais != null) {
                try {
                    bais.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return obj;
    }


}
